//
//  ZLW_RecommentDetailController.m
//  Otaku
//
//  Created by lanou3g on 16/5/7.
//  Copyright © 2016年 Liuwx. All rights reserved.
//

#import "ZLW_RecommentDetailController.h"
#import "ZLW_RecommmentDetailModel.h"
#import "RecommentDeatilCell.h"
#import "LoginViewController.h"

#import "ZLWBaseModel.h"
#import "ZLW_RecommentCell.h"
#import "ZLW_TextCell.h"
#import "ZLW_VideoCell.h"
#import "ZLW_BaseCell.h"
#import "VideoPlayView.h"
@interface ZLW_RecommentDetailController ()<UMSocialUIDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,VideoPlayViewDelegate,VideoTableViewCellDelegate>

@property (nonatomic, strong) UITableView *myTableView;

@property (nonatomic, strong) UITextField *myView;

@property (nonatomic, strong) NSMutableArray *sourceArray;

@property (nonatomic, strong) UIView *AddTextField;

@property (nonatomic, strong) NSMutableArray *SouceData;
@property (nonatomic, strong) VideoPlayView *playView;
@property (nonatomic, strong) ZLW_VideoCell *currentSelectedCell;
@property (nonatomic, assign) BOOL isFullScreenPlaying;
@property (nonatomic, assign) NSInteger currentPage;

@property (nonatomic, strong) NSString *tip;
@end

@implementation ZLW_RecommentDetailController

-(void)dealloc
{
    [self.myTableView removeObserver:[self.myTableView defaultHeader] forKeyPath:@"contentOffset"];

}
-(NSMutableArray *)SouceData
{
    if (_SouceData == nil) {
        _SouceData  = [NSMutableArray new];
    }
    return _SouceData;
}

-(NSMutableArray *)sourceArray
{
    if (nil == _sourceArray) {
        _sourceArray = [NSMutableArray new];
    }
    return _sourceArray;
}

- (UITableView *)myTableView
{
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, FUll_VIEW_WIDTH, FUll_CONTENT_HEIGHT - PageBtn) style:UITableViewStylePlain];
    }
    return _myTableView;
}
-(UITextField *)myView
{
    if (!_myView) {
        _myView = [[UITextField alloc] initWithFrame:CGRectMake(0, FUll_VIEW_HEIGHT- 110, FUll_VIEW_WIDTH , 50)];
    }
    return _myView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
     self.tabBarController.tabBar.alpha = 1;
    self.myTableView.separatorStyle = UITableViewCellAccessoryNone;
 
    self.view.backgroundColor = [UIColor whiteColor];
    [self laodNetWorking];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.myTableView registerNib:[UINib nibWithNibName:@"RecommentDeatilCell" bundle:nil] forCellReuseIdentifier:@"Re-Deatil-cell"];
    [self.view addSubview:self.myTableView];
  
    [self TextFieldUp];
  
    // Do any additional setup after loading the view.
    __weak typeof(self)weakSelf = self;
    [self.myTableView addRefreshWithRefreshViewType:(LORefreshViewTypeHeaderDefault) refreshingBlock:^{
        [weakSelf.sourceArray removeAllObjects];
        [weakSelf.myTableView reloadData];
        [weakSelf laodNetWorking];
    }];
  [self setupBasic];
    ///注册
    [self ReisterNib];
}
-(void)setupBasic {
    self.currentPage = 0;
    self.isFullScreenPlaying = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.myTableView.scrollIndicatorInsets = self.myTableView.contentInset;
}
///注册
-(void)ReisterNib
{
    [self.myTableView registerNib:[UINib nibWithNibName:@"ZLW_RecommentCell" bundle:nil] forCellReuseIdentifier:@"ZLW_RecommentModel"];
    
    [self.myTableView registerNib:[UINib nibWithNibName:@"ZLW_TextCell" bundle:nil] forCellReuseIdentifier:@"ZLW_TextModel"];
    
    [self.myTableView registerNib:[UINib nibWithNibName:@"ZLW_VideoCell" bundle:nil] forCellReuseIdentifier:@"ZLW_VideoModel"];
}

-(void)TextFieldUp
{
    self.myView.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:self.myView];
    self.myView.delegate = self;
    self.myView.placeholder = @"发表评论";
    self.myView.adjustsFontSizeToFitWidth = YES;
    self.myView.keyboardType = UIKeyboardTypeNamePhonePad;
    self.myView.textAlignment = NSTextAlignmentCenter;
    self.myView.enabled = YES;
    self.myView.clearsOnBeginEditing = UITextFieldViewModeUnlessEditing;
    self.myView.returnKeyType = UIReturnKeyGo;
    self.myView.borderStyle = UITextBorderStyleRoundedRect;

}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = self.view.frame;
    frame.origin.y -= 310;
    frame.size.height += 310;
    self.AddTextField = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - self.view.frame.origin.y +60 , FUll_VIEW_WIDTH, 80)];
    self.AddTextField.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:self.AddTextField];
    
   
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, 50, 50)];
    lable.text = @"分享:";
    lable.font = [UIFont systemFontOfSize:15];
    lable.textColor = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:1.0];
    
    UIButton *buttonShare = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [buttonShare setFrame:CGRectMake(60, 0, 60, 60)];
  
    NSString *path = [[NSBundle mainBundle] pathForResource:@"login_sina@3x" ofType:@"png"];
    UIImage *image = [[UIImage alloc] initWithContentsOfFile:path];
    [buttonShare setImage:image  forState:(UIControlStateNormal)];
    [buttonShare addTarget:self action:@selector(buttonShareAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIButton *buttonSend = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [buttonSend setFrame:CGRectMake(300, 0, 60, 60)];
    [buttonSend setTitle:@"发送" forState:(UIControlStateNormal)];
    [buttonSend addTarget:self action:@selector(buttonSendAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [buttonSend setTintColor:[UIColor purpleColor]];

    [self.AddTextField addSubview:lable];
    [self.AddTextField addSubview:buttonShare];
    [self.AddTextField addSubview:buttonSend];
    
    
    
    
    self.view.frame = frame;
    
   
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    if (self.isFullScreenPlaying == NO) {
        [self.playView resetPlayView];
        
    }
    self.navigationController.navigationBar.alpha = 1;
}

-(void)buttonShareAction:(UIButton *)sender
{
    [UMSocialSnsService presentSnsIconSheetView:[UIApplication sharedApplication].keyWindow.rootViewController appKey:@"572c6a8ce0f55ac72d000352" shareText:self.getmodel.content
                                     shareImage:[UIImage imageNamed:@"icon"]shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToDouban,UMShareToQzone,UMShareToEmail,UMShareToSms,nil]delegate:self];
    
}
-(void)buttonSendAction:(UIButton *)sender
{
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"" message:@"请登陆" preferredStyle:(UIAlertControllerStyleAlert)];
    [alertView addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil]];
    [self presentViewController:alertView animated:YES completion:nil];
   
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    CGRect frame = self.view.frame;
    frame.origin.y += 310;
    frame.size.height -= 310;
    self.view.frame = frame;
    
    [self.myView resignFirstResponder];
    return YES;
}



-(void)laodNetWorking
{
    [LWXNetWorkRequestManager requestURL:[NSURL URLWithString:RECOMMENDEDCOMMENT_URL] Method:LWX_GET Params:@{@"group_id":self.getmodel.group_id ,@"item_id":@6431281251,@"count":@20,@"offset":@0,@"iid":@4240136140,@"device_id":@15036532241,@"ac":@"wifi",@"channel":@"ucad",@"aid":@7,@"app_name":@"joke_essay",@"version_code":@500,@"version_name":@"5.0.0",@"device_platform":@"android",@"ssmix":@"a",@"device_type":@"HUAWEI+B199",@"os_api":@18,@"os_version":@"4.3",@"uuid":@"A000004F036FAC",@"openudid":@"e691cf971858edda",@"manifest_version_code":@500}  Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSDictionary *JsonDict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSDictionary *dataDict = JsonDict[@"data"];
            for ( NSDictionary *itemDict in dataDict[@"recent_comments"]) {
                ZLW_RecommmentDetailModel *model = [ZLW_RecommmentDetailModel new];
                [model setValuesForKeysWithDictionary:itemDict];
                [self.sourceArray addObject:model];
            }
        }
        [self.SouceData addObject:self.getmodel];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.myTableView reloadData];
            [[self.myTableView defaultHeader] endRefreshing];

        });
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.SouceData.count;
        
    }else
    {
       return self.sourceArray.count;
    }
    
    return 0;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        ZLW_BaseCell *cell = [ZLW_BaseCell cellWithTableView:tableView Model:self.SouceData[indexPath.row] IndexPath:indexPath];
        if ([cell isKindOfClass:[ZLW_VideoCell class]]) {
            ZLW_VideoCell *vcell = (ZLW_VideoCell*)cell;
            vcell.delegate = self;
            vcell.indexPath = indexPath;
            if (vcell.getmodel.mp4_url.length > 0) {
                vcell.getmodel = self.SouceData[indexPath.row];
            }
            
        }
        
        return cell;
    }else
    {
        RecommentDeatilCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Re-Deatil-cell"];
        cell.getmodel = self.sourceArray[indexPath.row];
        
        return cell;
    }
    return nil;
 
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.tabBarController.tabBar.alpha = 0;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        NSString *modelNameModel = NSStringFromClass([self.SouceData[indexPath.row] class]);
        NSString *modelName = [modelNameModel stringByReplacingOccurrencesOfString:@"Model" withString:@""];
        Class cellClass = NSClassFromString([modelName stringByAppendingString:@"Cell"]);
        
        CGFloat cellHeight = [cellClass heightModel:self.SouceData[indexPath.row]];
        return cellHeight;
    }
    else{
        CGFloat cellHoght = [[RecommentDeatilCell class] heightModel:self.sourceArray[indexPath.row]];
        return cellHoght;
        
    }
    return 0;
}

#pragma mark VideoTableViewCell的代理方法
-(void)clickVideoButton:(NSIndexPath *)indexPath
{
    [self.playView resetPlayView];
    ZLW_VideoCell *cell = [self.myTableView cellForRowAtIndexPath:indexPath];
    self.currentSelectedCell = cell;
    VideoPlayView *playView = [VideoPlayView videoPlayView];
    ZLW_VideoModel *model = self.SouceData[indexPath.row];
    playView.frame = model.videoFrame;
    [cell addSubview:playView];
    cell.playView = playView;
    self.playView = playView;
    self.playView.delegate = self;
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:model.mp4_url]];
    
    self.playView.playerItem = item;
}







@end
